#include "stdafx.h"
#include "table.h"

#include <QModelIndexList>
#include <QModelIndex>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSqlRecord>
#include <QCompleter>
#include <QDebug>

Table::Table(QWidget *parent) 
	: QDialog(parent)
{
    _model = new QSqlTableModel;
    _view = new QTableView;
    _view->setModel(_model);
	_view->setSortingEnabled(true);
	//_view->setSelectionBehavior(QAbstractItemView::SelectRows);
	_view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
 
    _model->setTable("setting");
	_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
 
    connect(_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(slotModelDataChanged(QModelIndex,QModelIndex)));
 
    _model->select();
 
    QVBoxLayout* vBox = new QVBoxLayout(this);
    vBox->addWidget(_view);
 
    QHBoxLayout* hBox = new QHBoxLayout;
    vBox->addLayout(hBox);
 
    hBox->addWidget(_add=new QPushButton("Add"));
    hBox->addWidget(_del=new QPushButton("Del"));
    hBox->addWidget(_revert=new QPushButton("Revert"));
    hBox->addWidget(_submit=new QPushButton("Submit"));
	hBox->addWidget(_ok = new QPushButton("OK"));
 
    connect(_add, &QPushButton::clicked, [&](){
        QSqlRecord record = _model->record();
        _model->insertRecord(-1, record);
    });

    connect(_del, &QPushButton::clicked, [&](){
		auto index = _view->selectionModel()->currentIndex();
		if (index.isValid())
		{
			_model->removeRow(index.row());
		}
	});

    connect(_revert, &QPushButton::clicked, [&](){
		_model->revert();
	});

    connect(_submit, &QPushButton::clicked, [&](){
        _model->submitAll();
    });

	connect(_ok, &QPushButton::clicked, [&](){
		_model->submitAll();
		QDialog::accept();
	});
}

QStringList Table::GetTexts() const
{
	QStringList list;
	int rowCount = _model->rowCount();
	for (int i = 0; i < rowCount; i++)
	{
		QString text = _model->record(i).value("text").toString();
		list.append(text);
	}

	return list;
}
